import { useEffect, useState, useCallback, FC, useRef } from "react";
import Taro from "@tarojs/taro";
import LicensePopTip from './LicensePopTip';


const LicensePopView: FC = ({ isTab }: { isTab?: boolean }) => {
  const [isPopupShow, setIsPopupShow] = useState<boolean>(false);
  const resolveRef = useRef();

  useEffect(() => {
    // 有的基础库没有，会报错，需要考虑兼容
    if (Taro.onNeedPrivacyAuthorization) {
      Taro.onNeedPrivacyAuthorization((resolve, eventInfo) => {
        console.log('触发本次事件的接口是：' + eventInfo.referrer, resolve)
        resolveRef.current = resolve;
        setIsPopupShow(true)
      })
    }
  }, [])

  const closePopup = useCallback(() => {
    setIsPopupShow(false);
    resolveRef.current && resolveRef.current({ event: 'disagree' })
    Taro.exitMiniProgram()
  }, []);

  return (
    <>
      <LicensePopTip isTab={isTab} isOpen={isPopupShow} closePopup={closePopup} onAgree={({ buttonId }) => {
        console.log('同意', { buttonId, event: 'agree' }, resolveRef.current);
        try {
          resolveRef.current && resolveRef.current({ buttonId, event: 'agree' })
        } catch (e) {
          console.log('调用授权resolve失败', e)
        }
        setIsPopupShow(false);
      }}
      />
    </>
  );
};

export default LicensePopView
